<template>
	<view class="submit-container">
		<view class="service-title">
			<text>{{serviceTypeText}}</text>
		</view>
		
		<view class="form-section">
			<view class="input-group">
				<view class="input-label required">标题</view>
				<input class="input-box" v-model="formData.title" placeholder="请简要描述您的问题" />
			</view>
			
			<view class="input-group">
				<view class="input-label required">详细描述</view>
				<textarea class="textarea-box" v-model="formData.content" placeholder="请详细描述您遇到的问题，以便我们更好地为您服务" />
			</view>
			
			<!-- <view class="input-group">
				<view class="input-label">联系电话</view>
				<input class="input-box" v-model="formData.contactPhone" type="number" placeholder="请输入您的联系电话" />
				<view class="input-tip">
					<text>可填写任意联系方式，方便工作人员与您沟通</text>
					<text v-if="!formData.contactPhone && userInfo.phone" class="use-phone" @click="useDefaultPhone">使用绑定手机号</text>
				</view>
			</view> -->
			
			<view class="input-group" v-if="serviceType === 'repair'">
				<view class="input-label">地点</view>
				<input class="input-box" v-model="formData.address" placeholder="请输入问题发生的具体地点" />
			</view>
			
			<view class="input-group">
				<view class="input-label">上传图片</view>
				<view class="image-upload-area">
					<view 
						class="image-item" 
						v-for="(item, index) in formData.images" 
						:key="index"
					>
						<image 
							class="preview-image" 
							:src="item" 
							mode="aspectFill"
							@error="handleImageError(index)"
						></image>
						<view class="delete-icon" @click="removeImage(index)">×</view>
					</view>
					
					<view class="upload-button" @click="chooseImage" v-if="formData.images.length < 3">
						<image class="upload-icon" src="/static/icons/upload.png"></image>
						<text class="upload-text">上传图片</text>
					</view>
				</view>
				<text class="upload-tip">最多上传3张图片，每张不超过2MB</text>
			</view>
		</view>
		
		<view class="action-area">
			<button class="submit-button" @click="handleSubmit">提交服务申请</button>
		</view>
	</view>
</template>

<script>
import { submitService } from '@/api/service.js';
import { getImageUrl } from '@/utils/image.js';
import { uploadImages } from '@/utils/upload.js';

export default {
	data() {
		return {
			serviceType: '',
			userInfo: {},
			formData: {
				title: '',
				content: '',
				contactPhone: '',
				address: '',
				images: []
			}
		}
	},
	computed: {
		serviceTypeText() {
			const typeMap = {
				'repair': '物业报修',
				'complaint': '投诉建议',
				'help': '生活求助'
			};
			return typeMap[this.serviceType] || '服务申请';
		}
	},
	onLoad(options) {
		if (options.type) {
			this.serviceType = options.type;
		} else {
			uni.showToast({
				title: '参数错误',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
		
		// 获取用户信息，但不自动填充手机号
		this.userInfo = uni.getStorageSync('userInfo') || {};
	},
	methods: {
		// 使用默认绑定的手机号
		useDefaultPhone() {
			if (this.userInfo && this.userInfo.phone) {
				this.formData.contactPhone = this.userInfo.phone;
			}
		},
		
		chooseImage() {
			// 直接调用选择图片
			this.doChooseImage();
		},
		
		// 执行选择图片
		doChooseImage() {
			uni.chooseImage({
				count: 3 - this.formData.images.length,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					console.log('选择图片原始返回：', JSON.stringify(res));
					
					// 检查返回的数据
					if (!res || !res.tempFilePaths || !Array.isArray(res.tempFilePaths)) {
						console.error('返回数据格式错误');
						uni.showToast({
							title: '选择图片失败：数据格式错误',
							icon: 'none'
						});
						return;
					}
					
					// 过滤掉无效的路径
					const validPaths = res.tempFilePaths.filter(path => {
						if (!path) {
							console.warn('发现无效的图片路径');
							return false;
						}
						return true;
					});
					
					if (validPaths.length === 0) {
						console.error('没有有效的图片路径');
						uni.showToast({
							title: '未获取到有效的图片',
							icon: 'none'
						});
						return;
					}
					
					// 检查文件类型（主要针对电脑端）
					// #ifdef H5
					// 在H5环境中，检查文件类型
					const files = res.tempFiles || [];
					if (files.length > 0) {
						for (let i = 0; i < files.length; i++) {
							const file = files[i];
							if (file && file.type && !file.type.startsWith('image/')) {
								uni.showToast({
									title: '请选择图片文件',
									icon: 'none'
								});
								return;
							}
						}
					}
					// #endif
					
					console.log("有效的图片路径:", validPaths);
					
					// 检查总数量
					const newTotalCount = this.formData.images.length + validPaths.length;
					if (newTotalCount > 3) {
						uni.showToast({
							title: '最多只能选择3张图片',
							icon: 'none'
						});
						return;
					}
					
					// 添加所有有效的图片
					for (const path of validPaths) {
						this.formData.images.push(path);
					}
					console.log('更新后的图片数组：', this.formData.images);
					
					// 显示预览
					this.$nextTick(() => {
						console.log('图片预览更新完成');
					});
				},
				fail: (err) => {
					console.error('选择图片失败：', err);
					// 如果是权限问题，引导用户去设置
					if (err.errMsg && err.errMsg.includes('permission')) {
						uni.showModal({
							title: '提示',
							content: '需要相册权限才能选择图片',
							confirmText: '去设置',
							success: (res) => {
								if (res.confirm) {
									// #ifdef APP-PLUS
									plus.runtime.openSettings();
									// #endif
									
									// #ifdef MP-WEIXIN
									wx.openSetting();
									// #endif
								}
							}
						});
					} else {
						uni.showToast({
							title: '选择图片失败：' + (err.errMsg || '未知错误'),
							icon: 'none'
						});
					}
				}
			});
		},
		
		// 移除图片
		removeImage(index) {
			this.formData.images.splice(index, 1);
		},
		
		// 上传图片
		async uploadImages() {
			if (this.formData.images.length === 0) {
				return '';
			}
			console.log("this.formData.images",this.formData.images);
			return await uploadImages(this.formData.images);
		},
		
		// 提交表单
		async handleSubmit() {
			// 表单验证
			if (!this.formData.title.trim()) {
				uni.showToast({
					title: '请输入标题',
					icon: 'none'
				});
				return;
			}
			
			if (!this.formData.content.trim()) {
				uni.showToast({
					title: '请输入详细描述',
					icon: 'none'
				});
				return;
			}
			
			// 如果填写了手机号，检查格式是否正确
			if (this.formData.contactPhone && !/^1\d{10}$/.test(this.formData.contactPhone)) {
				uni.showModal({
					title: '提示',
					content: '手机号格式不正确，是否仍要继续提交？',
					success: (res) => {
						if (res.confirm) {
							this.submitForm();
						}
					}
				});
				return;
			}
			
			// 上传图片
			let imageUrls = '';
			if (this.formData.images.length > 0) {
				try {
					imageUrls = await this.uploadImages();
					console.log(imageUrls);
					
					if (!imageUrls) {
						uni.hideLoading();
						uni.showModal({
							title: '提示',
							content: '图片上传失败，是否继续提交（不包含图片）？',
							success: (res) => {
								if (res.confirm) {
									this.submitData('');
								}
							}
						});
						return;
					}
				} catch (error) {
					console.error('图片上传失败：', error);
					uni.hideLoading();
					uni.showModal({
						title: '提示',
						content: '图片上传失败，是否继续提交（不包含图片）？',
						success: (res) => {
							if (res.confirm) {
								this.submitData('');
							}
						}
					});
					return;
				}
			}
			
			// 提交数据
			await this.submitData(imageUrls);
		},
		
		// 实际提交表单逻辑
		async submitForm() {
			// 显示提交中提示
			uni.showLoading({
				title: '提交中...',
				mask: true
			});

			try {
				// 表单验证
				if (!this.formData.title) {
					uni.hideLoading();
					uni.showToast({
						title: '请输入标题',
						icon: 'none'
					});
					return;
				}
				if (!this.formData.content) {
					uni.hideLoading();
					uni.showToast({
						title: '请输入内容',
						icon: 'none'
					});
					return;
				}

				// 上传图片
				let imageUrls = '';
				if (this.formData.images.length > 0) {
					try {
						imageUrls = await this.uploadImages();
						console.log("imageUrls",imageUrls);
						if (!imageUrls) {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: '图片上传失败，是否继续提交（不包含图片）？',
								success: (res) => {
									if (res.confirm) {
										this.submitData('');
									}
								}
							});
							return;
						}
					} catch (error) {
						console.error('图片上传失败：', error);
						uni.hideLoading();
						uni.showModal({
							title: '提示',
							content: '图片上传失败，是否继续提交（不包含图片）？',
							success: (res) => {
								if (res.confirm) {
									this.submitData('');
								}
							}
						});
						return;
					}
				}

				// 提交数据
				await this.submitData(imageUrls);
			} catch (error) {
				console.error('提交失败', error);
				uni.hideLoading();
				uni.showToast({
					title: error.message || '提交失败，请重试',
					icon: 'none'
				});
			}
		},

		// 提交数据
		async submitData(imageUrls) {
			try {
				// 将服务类型字符串转换为对应的整数类型
				const typeCodeMap = {
					'repair': 0,      // 物业报修
					'complaint': 1,   // 投诉建议
					'help': 2         // 生活求助
				};
				
				// 处理图片URL
				let processedImageUrls = '';
				if (imageUrls) {
					// 确保imageUrls是字符串
					if (typeof imageUrls === 'string') {
						processedImageUrls = imageUrls;
					} else if (Array.isArray(imageUrls)) {
						// 如果是数组，转换为逗号分隔的字符串
						processedImageUrls = imageUrls.join(',');
					} else {
						console.warn('图片URL格式不正确：', imageUrls);
					}
				}
				
				// 构建提交数据
				const submitData = {
					type: typeCodeMap[this.serviceType] !== undefined ? typeCodeMap[this.serviceType] : 0,
					title: this.formData.title,
					content: this.formData.content,
					contactPhone: this.formData.contactPhone,
					address: this.formData.address,
					images: processedImageUrls
				};

				console.log('准备提交的数据：', submitData);

				// 提交数据
				const res = await submitService(submitData);
				console.log('提交服务响应：', res);
				
				if (res.code === 200) {
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					// 设置全局标记，通知服务列表页面需要刷新
					const app = getApp();
					if (app.globalData) {
						app.globalData.serviceListNeedRefresh = true;
					}
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					throw new Error(res.message || '提交失败');
				}
			} catch (error) {
				console.error('提交服务失败：', error);
				throw error;
			} finally {
				uni.hideLoading();
			}
		},
		
		// 处理图片加载错误
		handleImageError(index) {
			console.error('图片加载失败，索引：', index);
			uni.showToast({
				title: '图片加载失败',
				icon: 'none'
			});
			// 移除加载失败的图片
			this.removeImage(index);
		},
		
	}
}
</script>

<style lang="scss" scoped>
.submit-container {
	min-height: 100vh;
	background-color: #f8f8f8;
	padding-bottom: 40rpx;
}

.service-title {
	background: linear-gradient(to right, #007AFF, #3498db);
	color: #fff;
	padding: 40rpx 30rpx;
	font-size: 34rpx;
	font-weight: bold;
}

.form-section {
	margin: 30rpx;
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.input-group {
	margin-bottom: 30rpx;
}

.input-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 16rpx;
	font-weight: 500;
}

.required::before {
	content: '* ';
	color: #FF5151;
}

.input-box {
	height: 80rpx;
	border: 1rpx solid #e0e0e0;
	border-radius: 8rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	width: 100%;
	box-sizing: border-box;
}

.input-tip {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 24rpx;
	color: #999;
	margin-top: 10rpx;
}

.use-phone {
	color: #007AFF;
	padding: 6rpx 12rpx;
	border-radius: 6rpx;
	background-color: rgba(0, 122, 255, 0.1);
}

.textarea-box {
	width: 100%;
	height: 240rpx;
	border: 1rpx solid #e0e0e0;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
	box-sizing: border-box;
}

.image-upload-area {
	display: flex;
	flex-wrap: wrap;
	margin-bottom: 10rpx;
}

.image-item {
	width: 200rpx;
	height: 200rpx;
	margin-right: 20rpx;
	margin-bottom: 20rpx;
	position: relative;
	border-radius: 8rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.preview-image {
	width: 200rpx;
	height: 200rpx;
	border-radius: 8rpx;
}

.delete-icon {
	position: absolute;
	top: -16rpx;
	right: -16rpx;
	width: 40rpx;
	height: 40rpx;
	background-color: rgba(0, 0, 0, 0.6);
	color: #fff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 26rpx;
}

.upload-button {
	width: 200rpx;
	height: 200rpx;
	border: 1rpx dashed #ccc;
	border-radius: 8rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #f8f9fa;
	transition: all 0.3s;
}

.upload-button:active {
	background-color: #e6f7ff;
}

.upload-icon {
	width: 60rpx;
	height: 60rpx;
	margin-bottom: 10rpx;
}

.upload-text {
	font-size: 24rpx;
	color: #999;
}

.upload-tip {
	font-size: 24rpx;
	color: #999;
}

.action-area {
	padding: 30rpx;
}

.submit-button {
	background: linear-gradient(to right, #007AFF, #3498db);
	color: #fff;
	border-radius: 45rpx;
	height: 90rpx;
	line-height: 90rpx;
	font-size: 32rpx;
	font-weight: 500;
	box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
	transition: all 0.3s;
}

.submit-button:active {
	transform: scale(0.98);
	box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.2);
}
</style> 